package org.Lin.server;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import static org.Lin.server.dbUtil.conn;

public class apiService {

    private static final Properties props = new Properties();
    static {
        try (InputStream input = apiService.class.getClassLoader().getResourceAsStream("config.properties")) {
            if (input == null) {
                throw new RuntimeException("找不到配置文件 config.properties");
            }
            props.load(input);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    private static final String QWEN_URL = props.getProperty("QWEN_API_URL");
    private static final String QWEN_API_KEY = props.getProperty("QWEN_API_KEY");
    private static final String DEEPSEEK_URL = props.getProperty("DEEPSEEK_API_URL");
    private static final String DEEPSEEK_API_KEY = props.getProperty("DEEPSEEK_API_KEY");
    static final String SYSTEM_PROMPT = props.getProperty("SYSTEM_PROMPT");

    public static LLMResponse callAvailableModel(String question, String currentModel, int currentQuestionId, String previousAnswer) {
        List<questionModel> recentConversations = getRecentConversations(currentQuestionId);

        if ("Qwen".equals(currentModel)) {
            return callLLMAPI(DEEPSEEK_URL, "deepseek-chat", DEEPSEEK_API_KEY, question, recentConversations, previousAnswer);
        } else if ("DeepSeek".equals(currentModel)) {
            return callLLMAPI(QWEN_URL, "qwen2.5-vl-32b-instruct", QWEN_API_KEY, question, recentConversations, previousAnswer);
        } else {
            int random = (int) (Math.random() * 2);
            if (random == 0) {
                return callLLMAPI(QWEN_URL, "qwen2.5-vl-32b-instruct", QWEN_API_KEY, question, recentConversations, previousAnswer);
            } else {
                return callLLMAPI(DEEPSEEK_URL, "deepseek-chat", DEEPSEEK_API_KEY, question, recentConversations, previousAnswer);
            }
        }
    }


    public static List<questionModel> getRecentConversations(int currentQuestionId) {
        List<questionModel> recentConversations = new ArrayList<>();
        String sql = "SELECT * FROM questions WHERE id != ? ORDER BY id DESC LIMIT 5";
        try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setInt(1, currentQuestionId);
            ResultSet rs = pstmt.executeQuery();
            while (rs.next()) {
                recentConversations.add(new questionModel(
                        rs.getInt("id"),
                        rs.getString("question"),
                        rs.getString("answer"),
                        rs.getString("model_used"),
                        rs.getString("user")
                ));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return recentConversations;
    }

    public static class LLMResponse {
        public final String content;
        public final String model;

        public LLMResponse(String content, String model) {
            this.content = content;
            this.model = model;
        }
    }
    private static LLMResponse callLLMAPI(String apiUrl, String model, String apiKey, String userText, List<questionModel> recentConversations, String previousAnswer) {
        try {
            URL url = new URL(apiUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setDoOutput(true);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Authorization", "Bearer " + apiKey);
            conn.setRequestProperty("Content-Type", "application/json");

            JSONObject jsonInput = new JSONObject();
            jsonInput.put("model", model);

            JSONArray messages = buildMessages(userText, recentConversations, previousAnswer);
            jsonInput.put("messages", messages);

            OutputStream os = conn.getOutputStream();
            os.write(jsonInput.toString().getBytes());
            os.flush();
            os.close();

            BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            StringBuilder response = new StringBuilder();
            String output;
            while ((output = br.readLine()) != null) {
                response.append(output);
            }
            conn.disconnect();

            String content = extractContentFromResponse(response.toString());
            String usedModel = extractModelFromResponse(response.toString());

            return new LLMResponse(content, usedModel);
        } catch (IOException e) {
            e.printStackTrace();
            return new LLMResponse("Error: " + e.getMessage(), "Unknown");
        }
    }

    private static String extractContentFromResponse(String jsonResponse) {
        try {
            JSONObject responseObj = new JSONObject(jsonResponse);
            JSONArray choices = responseObj.getJSONArray("choices");
            if (choices.length() > 0) {
                JSONObject message = choices.getJSONObject(0).getJSONObject("message");
                return message.getString("content");
            }
        } catch (Exception e) {
            System.err.println("解析 content 失败: " + e.getMessage());
            return "解析失败";
        }
        return "未找到 content 内容";
    }

    private static JSONArray buildMessages(String userText, List<questionModel> recentConversations, String previousAnswer) {
        JSONArray messages = new JSONArray();

        if (SYSTEM_PROMPT != null && !SYSTEM_PROMPT.isEmpty()) {
            JSONObject systemMessage = new JSONObject();
            systemMessage.put("role", "system");
            systemMessage.put("content", SYSTEM_PROMPT);
            messages.put(systemMessage);
        }

        for (questionModel q : recentConversations) {
            JSONObject userMessage = new JSONObject();
            userMessage.put("role", "user");
            userMessage.put("content", q.getQuestion());
            messages.put(userMessage);

            JSONObject assistantMessage = new JSONObject();
            assistantMessage.put("role", "assistant");
            assistantMessage.put("content", q.getAnswer());
            messages.put(assistantMessage);
        }

        if (previousAnswer != null && !previousAnswer.isEmpty()) {
            JSONObject assistantMessage = new JSONObject();
            assistantMessage.put("role", "assistant");
            assistantMessage.put("content", previousAnswer);
            messages.put(assistantMessage);
        }

        JSONObject currentUserMessage = new JSONObject();
        currentUserMessage.put("role", "user");
        currentUserMessage.put("content", userText);
        messages.put(currentUserMessage);

        System.out.println("messages: " + messages);
        return messages;
    }



    private static String extractModelFromResponse(String jsonResponse) {
        try {
            JSONObject responseObj = new JSONObject(jsonResponse);
            return responseObj.getString("model");
        } catch (Exception e) {
            System.err.println("无法解析 model 字段: " + e.getMessage());
            return "Unknown";
        }
    }

}